#####################################################################
#	$Id: Page.pm,v 1.1.1.1 2006/03/20 04:08:45 jfb Exp $
#
# Page.pm - class for handling Epiphyte template pages (.cnp files)
#
#
#####################################################################

package Epiphyte::Page;

use strict;
use vars qw($VERSION @ISA $CSSINC);

use IO::File;
use IO::Handle;

use Epiphyte::Log;


$VERSION = '0.01';

@ISA = qw(Exporter);

$CSSINC = "/css/main.css";


#####################################################################   
# new - class method
#
# Create a new species object
#####################################################################

sub new
{
	my ($class) = @_;

	my $self = {};

	bless($self, $class);

	return $self;
}

#####################################################################   
# parse - object method
#
# Parse a Epiphyte template file and generate the HTML.
#####################################################################

sub parse
{
	my ($class, $path) = @_;
	my $base = Epiphyte->getvar('BASEDIR');
	my $inbody = 0;
	my $ineval = 0;
	my $code;

#	my $css = "$class::CSSINC";
	my $css = $Epiphyte::Page::CSSINC;

	my $out = '';

	my $fh = new IO::File($path, O_RDONLY);
	if (!$fh) {
		Epiphyte->log(LOG_ERR, "failed to open $path: $!");
		return;
	}

	while (my $line = $fh->getline()) {
		if ($ineval) {
			$code .= $line;

			if ($line =~ /^}$/) {
				eval "$code";
				if ($@) {
					Epiphyte->log(LOG_ERR, "failed to eval: $@");
				}
				$ineval = 0;
			}
		} elsif ($line =~ /^\s*#/) {
			# Comment line, skip
			next;
		} elsif ($line =~ /^%(\w+)\s+(.*)$/) {
			if ($1 eq 'include') {
				my $sub_out = $class->parse($base . $2);
				$out .= $sub_out;
			} elsif ($1 eq 'head') {
				$out .= <<EOH;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel=StyleSheet href="$css" type="text/css" media="screen">
EOH

			} elsif ($1 eq 'title') {
				$out .= "<title>$2</title>\n";
			} elsif ($1 eq 'body') {
				if ($inbody) {
					Epiphyte->log(LOG_WARN,
					    "duplicate `%body' tag in page");
					next;
				}
				$out .= "</head>\n<body>\n";
				$inbody = 1;
			} elsif ($1 eq 'end') {
				$out .= "</body>\n</html>\n";
				last;
			} elsif ($1 eq 'eval') {
				$ineval = 1;
				$code = '';
				# Perl block
			}
		} elsif ($line =~ /^$/) {
			$out .= "<br>\n" if ($inbody);
		} else {
			$out .= $line;
		}
	}

	$fh->close();

	return ($out);
}


1;
